import { useState, useCallback, useMemo } from "react";
import { View, Text, TouchableOpacity, Keyboard } from "react-native";
import { TextInput, RadioButton } from "react-native-paper";
import { useSelector, useDispatch } from "react-redux";
import type { RootState } from "@/store/index";
import { setPlatformBaseUrl, setProxyUrl } from "@/store/slices/common";
import AntDesign from "react-native-vector-icons/AntDesign";
import NetInfo from "@react-native-community/netinfo";
import { setNetworkState, setNetworkType, setLastNetworkChangeTime } from "@/store/slices/common";
import globalMethods from "@/GlobalMethodProvider";
import Clipboard from "@react-native-clipboard/clipboard";

import styles from "./styles";
import config from "@/config";
import theme from "@/styles/theme";
import { getFmtTime } from "@/utils/date";
import { testNetInfo } from "@/api/home";

type StateType = {
  /** 平台基础 url */
  platformBaseUrl: string;
  /** 平台基础 url 错误提示 */
  platformBaseUrlErr: boolean;
  /** 代理接口 url */
  proxyUrl: string;
  /** 代理接口 url 错误提示 */
  proxyUrlErr: boolean;
};

/**
 * 网络诊断
 */
const NetworkDiagnosis = () => {
  const { common, index: storeIndex } = useSelector((state: RootState) => state);

  const [state, _setState] = useState<StateType>({
    platformBaseUrl: common.platformBaseUrl,
    platformBaseUrlErr: false,
    proxyUrl: common.proxyUrl,
    proxyUrlErr: false
  });

  // 通用更新状态(单个)
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 更新状态(多个)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  // api 状态
  const apiState = useMemo(() => {
    return {
      // 开发
      isDev: common.platformBaseUrl === config.DEV_PLATFORM_BASE_URL,
      // 内网生产
      isProd: common.platformBaseUrl === config.PROD_PLATFORM_BASE_URL
    };
  }, [common.platformBaseUrl]);

  // 网络类型
  const netTyep = apiState.isProd ? "内网" : "测试开发";

  const dispatch = useDispatch();

  /**
   * 切换网络标识
   * - DEV 开发
   * - PROD 内网生产
   */
  const setNetApi = (urlFlag: "DEV" | "PROD") => {
    let platformBaseUrl = "";
    let proxyUrl = "";
    if (urlFlag === "DEV") {
      platformBaseUrl = config.DEV_PLATFORM_BASE_URL;
      proxyUrl = config.DEV_PROXY_URL;
    } else if (urlFlag === "PROD") {
      platformBaseUrl = config.PROD_PLATFORM_BASE_URL;
      proxyUrl = config.PROD_PROXY_URL;
    }

    dispatch(setPlatformBaseUrl(platformBaseUrl));
    dispatch(setProxyUrl(proxyUrl));

    setObjState({
      platformBaseUrl,
      proxyUrl
    });

    const m = {
      DEV: "开发调试",
      PROD: "内网生产"
    };

    globalMethods.$showMessage({
      type: "toast",
      message: `接口切换为【${m[urlFlag]}】`
    });
  };

  // 重新获取网络信息
  const syncNetwork = async () => {
    try {
      const testNetRes = await testNetInfo().catch(err => {});
      const state = await NetInfo.fetch();
      console.log("重新获取网络信息", state);
      globalMethods.$success("已刷新", 1000);
      // 当前是否在线
      dispatch(setNetworkState(Boolean(testNetRes)));
      // 当前的网络类型
      dispatch(setNetworkType(state.type));
      dispatch(setLastNetworkChangeTime(getFmtTime()));
    } catch (err) {
      console.log("err: ", err);
    }
  };

  return (
    <View style={styles.comtainer}>
      <View style={[styles.networkInfoContainer, styles.border]}>
        <Text style={styles.text}>
          网络类型:
          <Text style={{ color: "#d9913d" }}> {common.networkType.toLocaleUpperCase()}</Text>
        </Text>
        <Text style={styles.text}>
          是否连接互联网:
          <Text style={{ color: common.networkState ? "green" : "red" }}> {common.networkState ? "是" : "否"}</Text>
        </Text>
        <Text style={styles.text}>
          是否连接后台WebSocket:
          {/* <Text style={{ color: common.networkState ? "green" : "red" }}> */}
          <Text style={{ color: "red" }}>{storeIndex.isWebsocketConnect ? "是" : "否"}</Text>
        </Text>
      </View>

      <View style={styles.tipsContainer}>
        <Text style={styles.lastTimeText}>最近网络更改时间: {common.lastNetworkChangeTime}</Text>
        <TouchableOpacity style={styles.syncContaienr} onPress={syncNetwork}>
          <AntDesign name="sync" size={18} />
        </TouchableOpacity>
      </View>

      <View style={[styles.ipSetContainer, styles.border]}>
        <View style={[styles.tipsContainer, { gap: 50 }]}>
          <Text>当前环境: {__DEV__ ? "开发" : "生产"}</Text>
          <Text>当前网络通信: {netTyep}</Text>
        </View>
        {config.IS_DEBUG && (
          <>
            <TouchableOpacity
              onPress={() => {
                Clipboard.setString(common.platformBaseUrl);
                globalMethods.$showMessage({
                  type: "toast",
                  message: `已复制【${common.platformBaseUrl}】`
                });
              }}
            >
              <Text style={styles.ipSetText}>当前平台URL: {common.platformBaseUrl}</Text>
            </TouchableOpacity>

            <TouchableOpacity
              onPress={() => {
                Clipboard.setString(common.proxyUrl);
                globalMethods.$showMessage({
                  type: "toast",
                  message: `已复制【${common.proxyUrl}】`
                });
              }}
            >
              <Text style={styles.ipSetText}>当前代理URL: {common.proxyUrl}</Text>
            </TouchableOpacity>
          </>
        )}

        {config.IS_DEBUG && (
          <View style={[styles.ipSetInput, { flexDirection: "row", alignItems: "center" }]}>
            <Text style={styles.ipSetText}>自定义切换: </Text>
            <View style={[styles.radioContainer, { flexDirection: "row", alignItems: "center" }]}>
              <TouchableOpacity style={styles.radioButton} onPress={() => setNetApi("DEV")}>
                <RadioButton
                  value="开发"
                  status={apiState.isDev ? "checked" : "unchecked"}
                  onPress={() => setNetApi("DEV")}
                />
                <Text style={{ color: apiState.isDev ? theme.primary : "#000" }}>开发</Text>
              </TouchableOpacity>

              <TouchableOpacity style={styles.radioButton} onPress={() => setNetApi("PROD")}>
                <RadioButton
                  value="生产"
                  status={apiState.isProd ? "checked" : "unchecked"}
                  onPress={() => setNetApi("PROD")}
                />
                <Text style={{ color: apiState.isProd ? theme.primary : "#000" }}>生产</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}

        {config.IS_DEBUG && (
          <View style={styles.ipSetInput}>
            <Text style={styles.ipSetText}>自定义输入: </Text>
            <TextInput
              dense
              mode="outlined"
              label="平台URL"
              placeholder="请输入平台URL"
              value={state.platformBaseUrl}
              error={state.platformBaseUrlErr}
              right={
                <TextInput.Icon
                  icon="close"
                  onPress={() => {
                    setObjState({ platformBaseUrl: "" });
                    Keyboard.dismiss();
                  }}
                />
              }
              onChangeText={text => {
                setObjState({
                  platformBaseUrl: text,
                  platformBaseUrlErr: false
                });
              }}
              onSubmitEditing={() => {
                dispatch(setPlatformBaseUrl(state.platformBaseUrl));
              }}
            />

            <TextInput
              dense
              mode="outlined"
              label="业务URL"
              placeholder="请输入业务URL"
              value={state.proxyUrl}
              error={state.proxyUrlErr}
              right={
                <TextInput.Icon
                  icon="close"
                  onPress={() => {
                    setObjState({ proxyUrl: "" });
                    Keyboard.dismiss();
                  }}
                />
              }
              onChangeText={text => {
                setObjState({
                  proxyUrl: text,
                  proxyUrlErr: false
                });
              }}
              onSubmitEditing={() => {
                dispatch(setProxyUrl(state.proxyUrl));
              }}
            />
          </View>
        )}

        {/* <Text style={styles.ipSetTip}>注意: 开发环境的平台接口有 /api</Text> */}
      </View>
    </View>
  );
};

export default NetworkDiagnosis;
